package cn.lds.healthexamspringboot.service.impl;

import cn.lds.healthexamspringboot.domain.User;
import cn.lds.healthexamspringboot.dto.HealthExamConstant;
import cn.lds.healthexamspringboot.dto.ResponseDTO;
import cn.lds.healthexamspringboot.exception.SysException;
import cn.lds.healthexamspringboot.mapper.UserMapper;
import cn.lds.healthexamspringboot.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeParseException;
import java.util.Objects;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseDTO<User> loginUser(User user) throws SysException {

        User loginUser = userMapper.loginUser(user);

        if (Objects.isNull(loginUser)){
            return ResponseDTO.buildError(HealthExamConstant.UserMsg.LOGIN_ERR);
        }


        return ResponseDTO.buildSuccess(loginUser);
    }

    @Override
    public ResponseDTO regUser(User user) throws SysException {

        User existingUser = null;
        // 检查手机号是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getMobileNo, user.getMobileNo());

        existingUser = userMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            throw new SysException(HealthExamConstant.UserMsg.REG_MOBILE_NO);
        }

        queryWrapper.eq(User::getIdNo, user.getIdNo());

        if (existingUser != null) {
            throw new SysException(HealthExamConstant.UserMsg.REG_ID_NO);
        }


        // 基础空值校验
        if (user.getIdNo() == null) {
            throw new IllegalArgumentException("身份证号码不能为空");
        }


        Pattern ID_PATTERN = Pattern.compile("^\\d{17}[\\dXx]$");


        // 正则验证格式
        if (!ID_PATTERN.matcher(user.getIdNo()).matches()) {
            throw new IllegalArgumentException("身份证格式不合法");
        }


        // 提取出生日期部分（YYYYMMDD）
        String birthDateStr = user.getIdNo().substring(6, 14);

        // 解析年、月、日
        int year, month, day;
        try {
            year = Integer.parseInt(birthDateStr.substring(0, 4));
            month = Integer.parseInt(birthDateStr.substring(4, 6));
            day = Integer.parseInt(birthDateStr.substring(6, 8));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("出生日期包含非数字字符", e);
        }

        // 创建出生日期对象
        LocalDate birthDate;
        try {
            birthDate = LocalDate.of(year, month, day);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("无效的出生日期", e);
        }

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算年龄
        user.setAge(Period.between(birthDate, currentDate).getYears());

        //用户注册，数据添加是自己，我们初始化为0
        user.setCreateBy(0L);

        int num = user.getIdNo().indexOf(16);

        if (num % 2 == 0 ){
            user.setGender("0");
        }else {
            user.setGender("1");
        }

        // 插入新用户
        int result = userMapper.insert(user);
        if (result > 0) {
            return ResponseDTO.buildSuccess();
        } else {
            return ResponseDTO.buildError("注册失败");
        }
    }

}
